# -*- coding: utf-8 -*-
"""
 Created by wq.wang on 2017/12/21
"""
import logging
from decimal import Decimal

from sanic.response import BaseHTTPResponse

from sanic import response
from settings import config
from wserver.base.exception import WWarniing
from wserver.base.service import Service

_logger = logging.getLogger(__name__)


class SanicService(Service):
    _abstract = True
    """

    """

    def __init__(self, request=None, api=None, *args, **kwargs):
        super().__init__(request, api, *args, *kwargs)

    @classmethod
    async def handle(cls, request, api='', *args, **kwargs):
        try:
            api = api or request.method.lower()
            try:
                api = cls._wapis[api]
            except Exception as e:
                _logger.exception(e)
                return response.text('<p>url not found</p>', status=404)

            data = api.parse_request(request, *args, **kwargs)
            _service = cls(request, api, *args, **kwargs)
            data = _service.init_data(data)
            method = getattr(_service, api.__name__)
            res = await method(**data)
            if isinstance(res, BaseHTTPResponse):
                return res
            elif isinstance(res, tuple):
                return response.json({"code": 0, "msg": "", "data": res[0], "count": res[1]}, )
            else:
                return response.json({"code": 0, "msg": "", "data": res}, )
        except WWarniing  as e:
            if config.get("DEBUG"):
                _logger.exception('业务错误')
            return response.json({"code": e.code, "msg": e.msg, "data": e.data}, )

    def init_data(self, data):
        return data

    @classmethod
    def gen_route(cls, base_url=""):
        urls = []
        base_url = base_url.strip('/')
        pre_url = getattr(cls, "pre_url", '').strip('/')
        url = "%s/%s" % (base_url, pre_url)
        url = url.lstrip('/')

        urls.append((url, cls.handle))
        urls.append(("%s/<api>" % url, cls.handle))
        return urls
